const jwt = require('jsonwebtoken')

const util = {
  tokenTime: 60 * 60 *2,

  checkUndefined(arr) {
    let flog = true;
    for (let i of arr) {
      if (i[i.label] === undefined) {
        flog = false
        break;
      } else {
        if (typeof i[i.label] !== i.type) {
          flog = false
          break;
        }
      }
    }
    return flog;
  },

  back(num, data = null) {
    let ctx;
    switch (num) {
      case -400:
        ctx = { code: -400, data, msg: '账号已存在' }
        break;

      case -401:
        ctx = { code: -401, data, msg: '用户名或密码错误' }
        break;

      case -402:
        ctx = { code: -402, data, msg: '用户未注册' }
        break;

      case -403:
        ctx = { code: -403, data, msg: '新密码不能和原密码一致' }
        break;

      case -201:
        ctx = { code: -201, data, msg: '权限验证失败' }
        break;

      case -101:
        ctx = { code: -101, data, msg: '参数验证失败' }
        break;

      case -102:
        ctx = { code: -102, data, msg: '短信发送失败' }
        break;

      case -103:
        ctx = { code: -103, data, msg: '验证码错误' }
        break;

      case -104:
        ctx = { code: -104, data, msg: '请忽频繁发送验证码' }
        break;

      case 500:
        ctx = { code: -103, data, msg: '服务器出错，请稍后再试' }
        break;
    }
    return ctx
  },

  regexp: {
    email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
    phone: /^1[3456789]\d{9}$/
  },

  async getTokenId(tokens) {
    const token = tokens.split(' ')[1]
    return await jwt.verify(token, 'anlin')
  },


  formatTime (date, symbol = '-') {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const formatNumber = (n) => {
      n = n.toString()
      return n[1] ? n : '0' + n
    }
    return [year, month, day].map(formatNumber).join(symbol) + ' ' + [hour, minute, second].map(formatNumber).join(':')
  },
}

module.exports = util;